package com.example.swim.controller;


import com.example.swim.Pojo.*;
import com.example.swim.Service.*;
import com.example.swim.Utils.R;
import org.json.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @author LiYa
 * @create 2022-07-15 9:13
 * 管理员的控制器
 */
@RestController
@RequestMapping("/web")
public class ManageController {
    //   管理员
    @Autowired
    AdminService adminService;
    //    近期活动信息
    @Autowired
    AcService acService;
    //    教练信息
    @Autowired
    CoachService coachService;
    //    开班信息
    @Autowired
    ClassRoomService classRoomService;
//    学员信息
    @Autowired
StudentService studentService;
//    会员信息
    @Autowired
    VipService vipService;
//    报名信息
    @Autowired
    ApplyService applyService;
//    公告
    @Autowired
    NewsService newService;
//登录
    @RequestMapping("/log")
    public R log(Admin loginForm)
    {
        AdminService admin;
        HashMap<String,Object> map=new HashMap<>();
        if(adminService.findAdmin(loginForm))
        {
            map.put("identity", "admin");
            map.put("user", loginForm);
            return new R(true,map);
        }
        return new R(false, "用户名或密码错误，请重新输入");
    }
    @RequestMapping("/main")
    public R toMain(Model model)
    {
        List<Student> students=studentService.findAll();
        List<Coach> coaches=coachService.findAll();
        List<ClassRoom> classes=classRoomService.findAll();
        List<VIP> vips=vipService.findAll();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("Vips", vips);
        map.put("classes", classes);
        map.put("Coaches",coaches);
        map.put("Students", students);
        return new R(true,map);
    }
//    增加教练
    @RequestMapping("/ManageCoach")
    public R MC(Coach coach)
    {
        coachService.insertCoach(coach);
//        通过使用重定向清理原先数据，如果不使用，在添加完教练后，删除教练会出错
        return new R(true, "添加成功");

    }
    @RequestMapping(value = "sf",method = RequestMethod.POST)
    @ResponseBody
    public R sf(@RequestParam("file") MultipartFile myfile, HttpServletRequest request) throws Exception
    {
        if(!myfile.isEmpty())
        {
//            得到文件存储路径
            String realPath="E:\\大三_上\\JAVAEE\\SpringBoot\\swim\\src\\main\\resources\\static\\images";
//          getOriginalFilename  得到文件名
            String fileName=myfile.getOriginalFilename();
            System.out.println(realPath);
            File f=new File(realPath,fileName);
//            判断目录是否存在
            if(!f.exists())
            {
//                创建目录
                f.mkdirs();
            }
//            transferTO将myfile内容写入到f目录中去
            myfile.transferTo(f);
            System.out.println("成功");
            return new R(true,"上传头像成功");
        }
        else
        {
           return new R(false,"上传失败");
        }
    }
//    上传excel表格
@ResponseBody
@RequestMapping(value = "inputExcel",method = RequestMethod.POST)
    public R getExcel(@RequestParam("file") MultipartFile file) throws Exception
    {
        if(!file.isEmpty())
        {
            System.out.println("正在上传");
            coachService.importExcel(file);
        }
        return new R(true,"导入教练成功");
    }
//    下载Excel文件
    @RequestMapping("/down")
    public String down(@RequestParam String downName,HttpServletRequest request,HttpServletResponse response)
    {
        String downPath="E:\\大三_上\\JAVAEE\\Coach.xlsx";
        FileInputStream in=null;//输入流
        ServletOutputStream out=null;
        try{
//            设置下载文件使用的报头
            response.setHeader("Content-Type","application/x-msdownload");
            response.setHeader("content-Disposition", "attachment;filename="
                    +toUTF8String(downName));
            in=new FileInputStream("E:\\大三_上\\JAVAEE\\下载");
            out=response.getOutputStream();
            out.flush();
            int read=0;
            byte b[]=new byte[1024];
            while((read=in.read())!=-1&in!=null)
            {
                out.write(b,0,read);
            }
            out.flush();
            in.close();
            out.close();
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return null;
    }
//    下载格式设置
    public String toUTF8String(String str)
    {
        StringBuffer sb=new StringBuffer();
        int len=str.length();
        for(int i=0;i<len;i++)
        {
            char c=str.charAt(i);
            if(c>=0&&c<=255)
            {
                sb.append(c);
            }
            else
            {
                byte b[];
                try
                {
                    b=Character.toString(c).getBytes("UTF-8");
                }
                catch (Exception e)
                {
                    e.printStackTrace();;
                    b=null;
                }
                for(int j=0;j<b.length;j++)
                {
                    int k=b[j];
                    if(k<0)
                    {
                        k&=255;
                    }
                    sb.append("%"+Integer.toHexString(k).toUpperCase());
                }
            }
        }
        return sb.toString();
    }
//    删除教练
    @RequestMapping("/deleteCoach")
    public R del(@RequestParam Integer id)
    {
        coachService.del(id);
        return new R(true, "删除成功");
    }
//    修改教练信息
    @PostMapping("/updateCoach")
    public R update(Coach coach)
    {
        System.out.println(coach.getAge());
        coachService.updateCoach(coach);
        return new R(true, "修改成功");

    }
//    添加学员
    @RequestMapping("/ManageStudent")
    public R ms(Student student) throws IOException {
//        拿来测试统一异常处理
//        if(student.getName().equals("123")){
//            throw new IOException();
//        }
        studentService.insert(student);
        return new R(true, "添加成功");

    }
//    删除学员
    @GetMapping("deleteStudent")
    public R delS(@RequestParam(value = "id", required = true) Integer id)
    {
        studentService.del(id);
        return new R(true,"删除成功");
    }
//    修改学员
    @RequestMapping("/updateStudent")
    public R updateS(Student student)
    {
        studentService.update(student);
        return new R(true, "修改成功");

    }
//    添加会员
    @RequestMapping("/ManageVip")
    public R insertVip(VIP vip)
    {
        vipService.insertVIP(vip);
        return  new R(true,"添加会员成功");
    }
//    删除会员
    @RequestMapping("/deleteVip")
    public R delVip(@RequestParam Integer id)
    {
        vipService.del(id);
        return new R(true, "删除成功");
    }
//    修改会员
    @RequestMapping("/updateVip")
    public R updateVip(VIP vip)
    {
        vipService.update(vip);
        return new R(true, "修改成功");
    }
//活动发布页面
    @GetMapping("/ManageActivity")
    public R MA(Model model)
    {
        List<Activity> ac=acService.findAll();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("Activities", ac);
        return new R(true,map);
    }
//    添加活动
    @RequestMapping("/AddActivity")
    public R add(Activity activity)
    {
        acService.insert(activity);
        return new R(true, "添加成功");

    }
//    删除活动
    @RequestMapping("deleteActivity")
    public R delA(@RequestParam Integer id)
    {
        acService.del(id);
      return new R(true,"删除活动成功");
    }
    //    修改活动
    @RequestMapping("/updateActivity")
    public R updateA(Activity activity)
    {
        acService.update(activity);
        return new R(true, "修改成功");

    }
    @GetMapping("/ManageNews")
    public R ms(){
        List<News> news=newService.getAll();
        return new R(true,news);
    }
//    添加公告
    @RequestMapping("/AddNews")
    public R addn(News news)
    {
        newService.insert(news);
        return new R(true, "添加成功");
    }
//    删除公告
    @RequestMapping("deleteNews")
    public R deln(@RequestParam Integer id)
    {
        newService.del(id);
      return new R(true,"删除活动成功");
    }
    //    修改公告
    @RequestMapping("/updateNews")
    public R updaten(News news)
    {
        newService.update(news);
        return new R(true, "修改成功");

    }
//    开班信息
    @GetMapping("ManageClassRoom")
    public R ManageClassRoom(Model model)
    {
        List<ClassRoom> classRooms=classRoomService.findAll();
        List<Apply> applies=applyService.findAll();
        Map<String,Object> map=new HashMap<String,Object>();
        map.put("applies", applies);
        map.put("classRooms", classRooms);
        return new R(true,map);
    }
    //    开班
    @RequestMapping("/AddClassRoom")
    public R addClassRoom(ClassRoom cr)
    {
        classRoomService.insertClassRoom(cr);
        return new R(true, "添加成功");

    }
    //    删除班
    @RequestMapping("deleteClassRoom")
    public R delClassRoom(@RequestParam Integer id)
    {
        classRoomService.delClassRoom(id);
        return new R(true, "删除成功");
    }
    //    修改班
    @RequestMapping("/updateClassRoom")
    public R updateClassRoom(ClassRoom cr)
    {
        System.out.println(cr.toString());
        classRoomService.updateClassRoom(cr);
        return new R(true, "修改成功");
    }
//    修改报名游客信息
    @RequestMapping("/updateApply")
    public  R updateApply(Apply apply)
    {
        applyService.update(apply);
        return new R(true, "修改成功");
    }
//    删除报名的游客
    @RequestMapping("/deleteApply")
    public R delApply(@RequestParam Integer id)
    {
        applyService.delById(id);
        return new R(true, "删除成功");
    }
//    报名处理
    @RequestMapping("/apply")
    public R apply(Student student)
    {
        studentService.insertNew(student);
        return new R(true, "报名成功");
    }
//    退出
    @RequestMapping("/logout")
    public String logout(HttpSession session)
    {
        session.invalidate();;
        return "redirect:/swim/index";
    }
}
